package org.mozhu.mboot.core.web.bind;

import org.apache.commons.lang3.StringUtils;
import org.mozhu.mboot.core.web.bind.annotation.ControllerDefaults;
import org.mozhu.mboot.core.web.controller.ConfigurableController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

public class ControllerDefaultsSupport implements BeanPostProcessor {

    private final static Logger LOGGER = LoggerFactory.getLogger(ControllerDefaultsSupport.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ConfigurableController) {
            ConfigurableController controller = (ConfigurableController) bean;
            ControllerDefaults controllerDefaults = AnnotationUtils.findAnnotation(bean.getClass(), ControllerDefaults.class);
            if (controllerDefaults != null) {
                String resourceIdentity = controllerDefaults.resourceIdentity();
                if (StringUtils.isNotBlank(resourceIdentity)) {
                    controller.setResourceIdentity(resourceIdentity);
                    LOGGER.debug("set property [reserouceIdentity={}] for bean [{}]", resourceIdentity, beanName);
                }
                String viewPrefix = controllerDefaults.viewPrefix();
                if (StringUtils.isNotBlank(viewPrefix)) {
                    controller.setViewPrefix(viewPrefix);
                    LOGGER.debug("set property [viewPrefix={}] for bean [{}]", viewPrefix, beanName);
                }
            }
        }
        return bean;
    }

}
